<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">


      <el-row v-show="showSearch" class="query_el_row-wrapper">
        <el-col :span="17">
          <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
            <el-form-item label="地块名称" prop="houseName">
              <el-input placeholder="请输入大棚名称" v-model="state.queryForm.houseName"/>
            </el-form-item>

            <el-form-item label="所属基地" prop="baseinfoId">
              <el-select v-model="state.queryForm.baseinfoId" placeholder="请选择所属基地">
                <el-option :key="index" :label="item.baseName" :value="item.id" v-for="(item, index) in thisPageState.baseInfoList"></el-option>
              </el-select>
            </el-form-item>


          </el-form>
        </el-col>
        <el-col :span="7">
          <div class="query_button_wrap">
            <el-button icon="search" type="primary" @click="getDataList">
              查询
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </div>
        </el-col>
      </el-row>



      <el-row class="add_el_row_wrapper">
        <el-col :span="15" class="add_el_button_el_col">
          <el-button icon="folder-add" type="primary" class="ml10" @click="formDialogRef.openDialog()"
                     v-auth="'farm_farmGreenhouse_add'">
            创建地块
          </el-button>
          <el-button plain :disabled="multiple" icon="Delete" type="primary"
                     v-auth="'farm_farmGreenhouse_del'" @click="handleDelete(selectObjs)">
            删除地块
          </el-button>
        </el-col>

        <el-col :span="9" class="right_tool_el_col">
          <div class="data_show_switch_wrapper" >
            <RightToolDataShowType v-model:dataShowType="dataShowType"></RightToolDataShowType>
<!--            <template v-for="(item,index) in dataShowTypeList" :key="index">-->
<!--&lt;!&ndash;              :color="dataShowStyleIsTable ? '#88968b' : '#128b0f'" &ndash;&gt;-->
<!--              <SvgIcon :name="item.icon +( dataShowType=== item.type ? ' active' : ' ')"-->
<!--                       @click="changeDataShowType(item)" :size="26"/>-->
<!--              <el-divider v-if="index<dataShowTypeList.length-1" direction="vertical"></el-divider>-->
<!--            </template>-->
          </div>


          <div style="margin-right: 10px"></div>
          <right-toolbar v-model:showSearch="showSearch" :export="'farm_farmGreenhouse_export'"
                         @exportExcel="exportExcel" class="ml10 mr20"
                         @queryTable="getDataList"></right-toolbar>


        </el-col>
      </el-row>

      <el-row class="data_list_show_el_row_wrapper">
<!--        <template v-if="dataShowType===dataShowTypeList[0].type" >-->
<!--          <div class="data_list_show_card_wrapper">-->
<!--            <div class="card_item" @click="testGoToHouseDev" v-for="(item,index) in state.dataList" :key="index">-->
<!--              <div class="title_wrapper">-->
<!--                <div class="title">{{ item.houseName }}</div>-->
<!--                <div class="detail_link">-->
<!--                  <div><SvgIcon name="iconfont icon-gengduo"></SvgIcon></div>-->
<!--                </div>-->
<!--              </div>-->
<!--              <div class="info_wrapper">-->
<!--                <div class="chart_wrapper">-->
<!--                  <v-chart class="pie_info_chart" :option="pieDapengChartOption" autoresize />-->

<!--                </div>-->
<!--              </div>-->
<!--              <div style="padding-left: 15px"><el-divider></el-divider></div>-->
<!--              <div class="footer_wrapper">-->
<!--                <el-image src="/devTest/img.png"></el-image>-->
<!--              </div>-->
<!--            </div>-->
<!--          </div>-->
<!--        </template>-->
        <template v-if="dataShowType === dataShowTypeList[0].type">
          <div class="data_list_show_card_wrapper">
            <div class="card_item" @click="testGoToHouseDev" v-for="(item, index) in state.dataList" :key="index">
              <div class="title_wrapper">
                <div class="title">{{ item.houseName }}</div>
                <div class="detail_link">
                  <div><SvgIcon name="iconfont icon-gengduo"></SvgIcon></div>
                </div>
              </div>
              <div class="info_wrapper">
                <div class="chart_wrapper">
                  <v-chart class="pie_info_chart" :option="pieDapengChartOption" autoresize />
                </div>
              </div>
              <div style="padding-left: 15px"><el-divider></el-divider></div>
              <div class="footer_wrapper">
                <el-row :gutter="20">
                    <el-card class="dashboard-card" shadow="hover" v-for="item in cardData" :key="item.title">
                      <div class="card-content">
                        <div class="card-icon">
                          <el-image :src="item.icon" fit="cover" class="icon-image" />
                        </div>
                        <div class="card-text">
                          <div class="card-number">{{ item.number }}</div>
                          <div class="card-title">{{ item.title }}</div>
                        </div>
                      </div>
                    </el-card>
                </el-row>
              </div>
            </div>
          </div>
        </template>
        <template v-if="dataShowType===dataShowTypeList[1].type">
          <div style="width: 100%;height: 1px"></div>
          <el-table fit="cover" :data="state.dataList" v-loading="state.loading"
                    :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
                    @selection-change="selectionChangHandle"
                    @sort-change="sortChangeHandle">
            <!--      border是为表格添加边框，  去掉边框-->
            <!--      <el-table :data="state.dataList" v-loading="state.loading" border-->
            <!--                :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"-->
            <!--                @selection-change="selectionChangHandle"-->
            <!--                @sort-change="sortChangeHandle">-->
            <el-table-column type="selection" width="40" align="center"/>
            <el-table-column type="index" label="#" width="40"/>
            <el-table-column prop="houseImg" label="大棚图片"  width="210">
              <template #default="scope">
                <div style="width: 100%;cursor: pointer" @click="previewImg(scope,true)">
                  <el-image :src="thisPageState.imgBaseUrl+scope.row.houseImg" :fit="'cover'" style="width: 180px;height: 100px">

                  </el-image>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="houseName" label="大棚名称" show-overflow-tooltip/>
            <el-table-column prop="houseArea" label="大棚面积（单位平方米）" show-overflow-tooltip/>
            <el-table-column prop="baseinfoId" label="所属基地的主键ID" show-overflow-tooltip/>
            <el-table-column prop="createBy" label="创建者" show-overflow-tooltip/>
            <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip/>
            <el-table-column prop="updateTime" label="更新时间" show-overflow-tooltip/>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button icon="edit-pen" text type="primary" v-auth="'farm_farmGreenhouse_edit'"
                           @click="formDialogRef.openDialog(scope.row.id)">编辑
                </el-button>
                <el-button icon="delete" text type="primary" v-auth="'farm_farmGreenhouse_del'"
                           @click="handleDelete([scope.row.id])">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>

      </el-row>

      <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination"/>




    </div>

    <!-- 编辑、新增  -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)"/>


    <!--  预览原始抓取图片-->
    <el-image-viewer v-if="thisPageState.showImg" :url-list="thisPageState.imgList"
                     :initial-index="thisPageState.imgViewIndex" @close="thisPageState.showImg=false">
    </el-image-viewer>
  </div>
</template>

<script setup lang="ts" name="systemFarmGreenhouse">
import {Ref } from 'vue';

/**
 * 引入使用vcharts组件
 */
import VChart, { THEME_KEY } from 'vue-echarts';
import {  provide } from 'vue';

/**
 * 针对不同的图表按需引入对应的内容
 */
import { use } from 'echarts/core'
import { PieChart } from 'echarts/charts'
import {
  TooltipComponent,
  LegendComponent,
  GraphicComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import type { ComposeOption } from 'echarts/core'
import type { PieSeriesOption } from 'echarts/charts'
import type {
  TooltipComponentOption,
  LegendComponentOption,
  GraphicComponentOption
} from 'echarts/components'

use([
  TooltipComponent,
  LegendComponent,
  GraphicComponent,
  PieChart,
  CanvasRenderer
])

type EChartsPieOption = ComposeOption<
    | TooltipComponentOption
    | LegendComponentOption
    | GraphicComponentOption
    | PieSeriesOption
    >



import {BasicTableProps, useTable} from "/@/hooks/table";
import {fetchList, delObjs} from "/@/api/farm/farmGreenhouse";
import { fetchList as fetchBaseInfoList } from "/@/api/farm/farmBaseinfo";
import axios from 'axios';
import {useMessage, useMessageBox} from "/@/hooks/message";
import {useDict} from '/@/hooks/dict';

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
// 定义查询字典

// 定义变量内容
const formDialogRef = ref()
// 搜索变量
const queryRef = ref()
const showSearch = ref(true)
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)

const dataShowTypeList=ref([
  {
    icon:"iconfont icon-liebiao1",
    type:"card"
  },
  {
    icon:"iconfont icon-liebiao",
    type:"table"
  },
])

//定义是表格显示 还是卡片显示
const dataShowType=ref("")
dataShowType.value=dataShowTypeList.value[0].type


const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: fetchList,
  handleDataListcallBack: getPreviewImagListByDataTable,
})

//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state)

// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields()
  // 清空多选
  selectObjs.value = []
  getDataList()
}

// 导出excel
const exportExcel = () => {
  downBlobFile('/farm/farmGreenhouse/export', Object.assign(state.queryForm, {ids: selectObjs}), 'farmGreenhouse.xlsx')
}

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({id}) => id);
  multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};

/**
 * 更换数据显示样式
 * @param showType
 */
const changeDataShowType=(showType)=>{
  dataShowType.value=showType.type
}


/**
 * 去除模板中直接使用的statu自定义一个自己需要使用的 页面state
 */
const thisPageState=reactive({
  baseInfoList:[],//所有基地信息
  imgBaseUrl:"/api", //后端地址 预览图片
  showImg:false,
  imgList:[],
  imgViewIndex:0,


})

/**
 * 获取后端地址
 */
thisPageState.imgBaseUrl=import.meta.env.VITE_API_URL

/**
 * 获取所有基地信息
 */
function getBaseInfoList(){
  fetchBaseInfoList().then(res=>{
    console.log(res)
    thisPageState.baseInfoList=res.data.records;
  })
}
getBaseInfoList()




/**
 * 获取数据图片的预览列表
 */
function getPreviewImagListByDataTable(){
  let list=[]
  list = state.dataList?.map(v => thisPageState.imgBaseUrl+v.houseImg) ?? [];
  thisPageState.imgList=list
}


/**
 * 预览图片
 * @param scope
 * @param isDetected
 */
function previewImg(scope){
  console.log(scope)
  thisPageState.showImg=true
  thisPageState.imgViewIndex=scope.$index
}



function getRandomInt(min, max) {
  min = Math.ceil(min); // 确保最小值是整数
  max = Math.floor(max); // 确保最大值是整数
  return Math.floor(Math.random() * (max - min + 1)) + min; // 包含 min 和 max
}
/**
 * 统计图
 */
const ranDomTestTata=[
  { value: getRandomInt(1,10), name: '巡检机器人' },
  { value: getRandomInt(1,10), name: '氮磷钾设备' },
]
const pieDapengChartOption:Ref<EChartsPieOption>=ref({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '43%',
    left: '300'
  },

  // 添加 graphic 配置
  graphic: [
    {
      type: 'text', // 文本类型
      // left: 'center', // 水平居中
      top: 'center', // 垂直居中
      x:120,
      // y:500,
      originX:100,
      style: {
        text: '设备总数\n( '+(ranDomTestTata[0].value + ranDomTestTata[1].value).toString() +')',  // 显示总数
        fontSize: 17,
        fontWeight: 'bold',
        fill: '#333', // 文本颜色

        textAlign:"center"
      }
    }
  ],
  series: [
    {
      width:"100%",
      left:"1",
      center:["120","50%"],
      name: 'Access From',
      type: 'pie',
      radius: ['70%', '90%'],
      label: {
        show: false,
        position: 'center'
      },

      data: ranDomTestTata
    }
  ]
})

// 小卡片数据
const cardData = ref<CardItem[]>
    ([
      {
        number: '18',
        title: '传感器',
        icon: 'public/devTest/sensor-line.png'
      },
      {
        number: '13',
        title: '控制器',
        icon: 'public/devTest/controller.png'
      },
      {
        number: '7',
        title: '摄像头',
        icon: 'public/devTest/monitor.png'
      },
      {
        number: '25',
        title: '预警消息',
        icon: 'public/devTest/notification.png'
      }
    ]);

const router=useRouter()
function testGoToHouseDev(){
  router.push("/iot/iotDevice/index")
}
</script>

<style lang="scss" scoped>
.footer_wrapper {
  padding: 20px;
  width: 100%;

  .el-row {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between; // 添加这行让卡片均匀分布

    .dashboard-card {
      height: 10vh;
      cursor: pointer;
      transition: all 0.3s;
      margin-left: 11px; // 添加左侧间距
      margin-right: 5px; // 添加右侧间距
      min-width: calc(25% - 20px); // 确保每行最多4个卡片，减去间距

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
      }

      &:last-child {
        margin-right: 0; // 最后一个卡片不需要右边距
      }

      .card-content {
        display: flex;
        align-items: center;
        height: 100%;
        width: 6vw;

        .card-icon {
          width: 45px;
          height: 30px;
          margin-right: 10px;
          display: flex;
          align-items: center;
          justify-content: center;

          .icon-image {
            width: 30px;
            height: 30px;
          }
        }

        .card-text {
          text-align: left;
          width: 100%;

          .card-number {
            font-size: 18px;
            font-weight: bold;
            color: var(--el-color-primary);
          }

          .card-title {
            font-size: 12px;
            color: var(--el-text-color-secondary);
          }
        }
      }
    }
  }
}
</style>